<?php
namespace app\admin\controller;

use think\Db;
use app\common\controller\AdminBase;
use app\common\model\AdminUser as AdminUserModel;
use app\common\model\Domain as DomainModel;

class Domain extends AdminBase
{
	protected $domain_model;
	protected $admin_user_model;

	public function _initialize(){
		parent::_initialize();
		$this->domain_model = new DomainModel();
		$this->admin_user_model = new AdminUserModel();
	}

	public function index($page = 1){
		$map = [];
		if($this->admin_id == 1){
			$url = url('admin/domain/author');
			$js = <<<EOF
			function author_user(cid){
				layer.open({
				  title: '域名授权'
				  ,area:['500px','400px']
				  ,type: 2
				  ,content: '$url?id='+cid
				});
			};
EOF;
			$this->assign('js_template',$js);
		} else {
			$map['admin_id'] = $this->admin_id;
			$this->assign('js_template','');
		}
		$domain_list = $this->domain_model->where($map)->paginate(15,false,['page'=>$page]);
		$url = ORIGIN_URL.'api/Order/getmsg/cid/';
		$this->assign('domain_list',$domain_list);
		$this->assign('admin_id',$this->admin_id);
		$this->assign('url', $url);
		return $this->fetch();
	}

	public function add(){
		return $this->fetch();
	}

	public function save(){
		if($this->request->isPost()){
			$data = $this->request->post();
			$result = $this->domain_model->allowField(true)->save($data);
			if($result){
				$this->success('保存成功');
			}else{
				$this->error('保存失败');
			}
		}
	}

	public function edit($id){
		$result = $this->domain_model->where('id',$id)->find();
		$this->assign('domain_msg',$result);
		return $this->fetch();
	}

	public function update($id){
		if($this->request->isPost()){
			$data = $this->request->post();
			$result = $this->domain_model->allowField(true)->where('id',$id)->update($data);
			if($result){
				$this->success('修改成功');
			}else{
				$this->error('修改失败');
			}
		}
	}

	public function delete($id){
		Db::name('xdmsg')->where('cid',$id)->delete();
		$result = $this->domain_model->where('id',$id)->delete();
		if($result){
			$this->success('删除成功');
		}else{
			$this->error('删除失败');
		}
	}

	public function author($id){
		if($this->request->isPost()){
			$data = $this->request->post(['author_id','id']);

			$result = $this->domain_model->where('id',$data['id'])->update(['admin_id' => $data['author_id']]);
			if($result){
				return $this->success('添加成功');
			}

			return $this->error('添加失败');
		} else {
			$map = [
				'id' => ['gt',1],
				'status' => 1,
			];
			$user_list = $this->admin_user_model->field('id,username')->where($map)->select();
			$author_id = $this->domain_model->where('id',$id)->value('admin_id');
			$this->assign('author_id',$author_id);
			$this->assign('id',$id);
			$this->assign('user_list',$user_list);
			return $this->fetch();
		}
	}
}